package com.taptech.doufu.presenter.home;

import android.app.Activity;
import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taptech.doufu.bean.DFHomeNovelBeans;
import com.taptech.doufu.bean.choice.CategoryTitleModel;
import com.taptech.doufu.bean.choice.NewUserGiftModel;
import com.taptech.doufu.constant.SelectBlockTypes;
import com.taptech.doufu.listener.CommmonImp;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.bean.choice.BannerModel;
import com.taptech.doufu.bean.choice.BlockModel;
import com.taptech.doufu.bean.choice.ChoiceTopicBean;
import com.taptech.doufu.bean.choice.ComicModel;
import com.taptech.doufu.bean.choice.NovelModel;
import com.taptech.doufu.bean.choice.TagModel;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.util.CacheUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Wyatt on 2017/10/13/013.
 */

public class ChoiceTopicPresenter {
    public interface OnHomeTopicView{
        void onTopicNext(List<ChoiceTopicBean> list, boolean isCache);
        void onTopicError();
    }

    private OnHomeTopicView onHomeTopicView;
    private Context mContext;

    public ChoiceTopicPresenter(Context context,OnHomeTopicView onHomeTopicView) {
        this.onHomeTopicView = onHomeTopicView;
        mContext = context;
    }

    /**
     * 获取缓存
     */
    public void loadTopicCache() {
        Observable.create(new Observable.OnSubscribe<List<ChoiceTopicBean>>() {
                    @Override
                    public void call(Subscriber<? super List<ChoiceTopicBean>> subscriber) {
                        org.json.JSONObject json = CacheUtil.readJsonDataFromCache(new File(CommmonImp.Home_choice_list));
                        List<ChoiceTopicBean> list = formatData(json.toString());
                        subscriber.onNext(list);
                    }
                })
                .compose(RxJavaHelper.<List<ChoiceTopicBean>>observeOnMainThread((Activity) mContext))
                .subscribe(new BaseSubscriber<List<ChoiceTopicBean>>(){
                    @Override
                    public void onNext(List<ChoiceTopicBean> list) {
                        super.onNext(list);
                        if (onHomeTopicView != null && list!=null) {
                            onHomeTopicView.onTopicNext(list,true);
                        }
                    }
                });
    }

    /**
     * 获取话题数据
     */
    public void getTopic(final boolean isUseCache,int young) {

        Call<ResponseBody> call =  ApiClient.getInstance().setUseCache(isUseCache).getService().getChoiceTopic(young);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                try {
                    String json = new String(response.body().bytes());
                    CacheUtil.saveJsonDataToCache(json,new File(CommmonImp.Home_choice_list));
                    onHomeTopicView.onTopicNext(formatData(json),isUseCache);
                } catch (Exception e) {
                    onHomeTopicView.onTopicError();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                onHomeTopicView.onTopicError();
            }
        });
    }

    private List<ChoiceTopicBean> formatData(String json) {
        List<ChoiceTopicBean> items = new ArrayList<>();
        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray list = data.getJSONArray("list");
        for (int i = 0; i < list.size(); i++) {
            ChoiceTopicBean bean = new ChoiceTopicBean();
            JSONObject object = list.getJSONObject(i);
            if (object.containsKey("title")) {
                String title = object.getString("title");
                bean.setTitle(title);
            }
            if (object.containsKey("moreUrl")) {
                String moreUrl = object.getString("moreUrl");
                bean.setMoreUrl(moreUrl);
            }
            if (object.containsKey("moreType")) {
                int moreType = object.getInteger("moreType");
                bean.setMoreType(moreType);
            }
            if (object.containsKey("replaceUrl")) {
                bean.setReplaceUrl(object.getString("replaceUrl"));
            }
            if (object.containsKey("subTitle")) {
                bean.setSubTitle(object.getString("subTitle"));
            }
            if (object.containsKey("deadline")) {
                bean.setDeadline(object.getString("deadline"));
            }
            if (object.containsKey("type")) {
                int type = object.getInteger("type");
                bean.setType(type);
                if (type == SelectBlockTypes.NEW_BOOKS) {
                    if (object.containsKey("list")) {
                        JSONArray jsonArray = object.getJSONArray("list");
                        List<ChoiceTopicBean> tempList = new ArrayList<>();
                        for (int j = 0; j < jsonArray.size(); j++) {
                            JSONObject obj = jsonArray.getJSONObject(j);
                            ChoiceTopicBean model = new ChoiceTopicBean();
                            model.setTitle(obj.getString("title"));
                            model.setMoreUrl(obj.getString("moreUrl"));
                            model.setNovelList(JSON.parseArray(obj.getString("list"),NovelModel.class));
                            tempList.add(model);
                        }
                        bean.setComplexList(tempList);
                    }
                } else if (type == SelectBlockTypes.TAGS) {
                    if (object.containsKey("list")) {
                        String array = object.getString("list");
                        bean.setTagList(JSON.parseArray(array,TagModel.class));
                    }
                } else if (type == SelectBlockTypes.NOTICE_BLOCK) {
                    if (object.containsKey("list")) {
                        String array = object.getString("list");
                        List<BannerModel> bannerModelList = JSON.parseArray(array, BannerModel.class);
                        if (bannerModelList != null && bannerModelList.size() > 0) {
                            bean.setBannerModel(bannerModelList.get(0));
                        }
                    }
                } else if (type == SelectBlockTypes.COMICS) {
                    if (object.containsKey("list")) {
                        String array = object.getString("list");
                        bean.setComicList(JSON.parseArray(array,ComicModel.class));
                    }
                } else if (type == SelectBlockTypes.STAR_AUTHOR) {
                    if (object.containsKey("list")) {
                        String array = object.getString("list");
                        bean.setAuthorList(JSON.parseArray(array, DFHomeNovelBeans.class));
                    }
                } else if(type == SelectBlockTypes.NEW_USER_GIFT){
                    if (object.containsKey("list")) {
                        List<NewUserGiftModel> list1 = JSON.parseArray(object.getString("list"), NewUserGiftModel.class);
                        if (list1 != null && list1.size() > 0) {
                            bean.setNewUserGiftModel(list1.get(0));
                        }
                    }
                } else if (type == SelectBlockTypes.CATEGORY_RECOMMEND) {
                    if (object.containsKey("list")) {
                        String array = object.getString("list");
                        bean.setNovelList(JSON.parseArray(array, NovelModel.class));
                    }
                    if (object.containsKey("blocks")) {
                        String blocks = object.getString("blocks");
                        bean.setCategoryTitleBlocks(JSON.parseArray(blocks, CategoryTitleModel.class));
                    }
                } else {
                    if (object.containsKey("list")) {
                        String array = object.getString("list");
                        bean.setNovelList(JSON.parseArray(array, NovelModel.class));
                    }
                    if (object.containsKey("blocks")) {
                        String blocks = object.getString("blocks");
                        bean.setBlocks(JSON.parseArray(blocks, BlockModel.class));
                    }
                }
            }
            items.add(bean);
        }
        return items;
    }

}
